new Vue({
    el: '#app',
    data: {
        loadingGetNotes: false,
        loadingAddNote: false,
        // 是否显示添加笔记的输入框
        showAddNoteCard: false,
        loading: false,
        // 是否开始练习
        doing: false,
        // 用户信息
        userInfo: userInfo != null ? userInfo : {
            id: null,
            nickname: "未登录"
        },
        // 卡片边框颜色
        cardBorderColor: [],
        solveResult: '(🔎解答题请自行比较答案)',
        // 练习题目的方式
        questionMethod: {
            // 选择的题型
            checkboxQuestions: [],
            // 选择的分类
            categoryIds: [],
            // 答案验证方式
            validateMethod: null
        },
        // 题型
        questionKinds: ['选择题', '填空题', '判断题', '解答题'],
        // 分类
        categories: [],
        validateMethods: [{
            value: '1',
            label: '做完一题立刻比对答案'
        }, {
            value: '2',
            label: '做完全部统一比对答案'
        }],
        // 完成了所有题目
        finished: false,
        // 选项标号
        options: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
        // 答案比对方式是做一题立即比对
        isValidateNow: true,
        // 当前题目在questions中的序号
        currentIdx: 0,
        // 当前题目内容
        currentQuestion: '',
        // 选项内容
        currentChoices: [],
        // 当前题目我的答案
        currentMyAnswer: '',
        // 当前题目结果
        currentResult: '',
        // 当前题目正确答案
        currentCorrectAnswer: '',
        // 当前题目id
        currentQuestionId: '',
        // 当前已选择的选项
        currentSelected: [],
        // 当前填写的内容
        currentBlanks: [],
        // 当前题目是否已经比对答案
        currentValidated: false,
        // 当前题目类型
        currentQuestionKind: null,
        // 全部练习题目
        questions: [],
        // 当前题目的笔记
        currentNotes: [{
            id: '1',
            content: '111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111'
        }],
        // 所有题目的笔记
        allNotes: [],
        // 新增笔记
        note: {
            content: '',
            open: false
        },
        openStatus: ['不公开', '公开'],
        // 正在修改笔记
        updatingNote: false,
        updateNote: {},
        loadingEditNote: false,
        curPrefixUrl: prefixUrl + gatewayPrefix.question
    },
    methods: {
        // 点击了开始练习
        start() {
            if (this.questionMethod.checkboxQuestions.length === 0) {
                showAlert(this, '请至少选择一种题型');
                return;
            }
            if (this.questionMethod.validateMethod === null) {
                showAlert(this, '请选择答案验证方式');
                return;
            }
            // 清空
            this.questions = [];
            // showMsg(this, 'questionMethod=' + JSON.stringify(this.questionMethod));
            this.isValidateNow = this.questionMethod.validateMethod === '1';

            this.getMyQuestionByCondition();
        },
        // 重新练习
        doAgain() {
            this.initValue();
        },
        // 根据数字设置字母答案
        genAnswer(string) {
            string = string.trim();
            // console.log('string=' + string)
            let ans = '';
            let idx;
            for (let i = 0; i < string.length; i++) {
                idx = parseInt(string[i])
                ans += this.options[idx];
            }
            return ans;
        },
        // 查询题目
        getMyQuestionByCondition() {
            this.loading = true;

            const categoryIds = this.questionMethod.categoryIds;
            const questionQueryDTO = {
                kinds: this.questionMethod.checkboxQuestions,
                categoryIds: categoryIds
            }
            const url = this.curPrefixUrl + "/user/questions/condition/my";

            axios.post(url, questionQueryDTO).then((resp) => {
                const result = resp.data;

                // data：ChoiceQuestionVO
                const data = result.data;
                // console.log("data="+JSON.stringify(data));

                // 如果没有题目
                if (data.length === 0) {
                    showAlert(this, msgConstant.noQuestion);
                    return;
                }
                // 标志开始练习
                this.doing = true;

                // 添加数据到表格中
                this.addQuestionToQuestions(data);
            }).finally(() => {
                this.loading = false;
            });
        },
        // 添加数据到questions中
        addQuestionToQuestions(data) {
            let questions = [];
            for (let i = 0; i < data.length; i++) {
                // console.log("i=" + i + ",data[i]=" + JSON.stringify(data[i]))
                let choices = [];
                let correctAnswer = '';
                let questionContent = '';
                let blanks = [];
                // 题目内容
                questionContent = data[i].question;
                // 如果是选择题
                if (data[i].kind === questionKind.choice) {
                    // 选项
                    choices = data[i].choice.trim().split(split.default);
                    // 正确答案
                    correctAnswer = this.genAnswer(data[i].answer);
                    if (data[i].answer.trim().length > 1) {
                        questionContent += "(多选)";
                    }
                }
                // 如果是填空题
                else if (data[i].kind === questionKind.blank) {
                    // 生成正确答案
                    const sp = data[i].answer.trim().split(split.default);
                    for (let j = 0; j < sp.length; j++) {
                        correctAnswer += (sp[j] + ' ');
                        // 设置当前填空为空
                        blanks.push('');
                    }
                }
                // 如果是判断题
                else if (data[i].kind === questionKind.judge) {
                    // 正确答案
                    if (data[i].answer.trim() === '0') {
                        correctAnswer = judge.yes;
                    } else {
                        correctAnswer = judge.no;
                    }
                }
                // 如果是解答题
                else if (data[i].kind === questionKind.solve) {
                    // 正确答案
                    correctAnswer = data[i].answer;
                }
                const question = {
                    id: data[i].id,
                    question: questionContent,
                    choices: choices,
                    selected: [],
                    myAnswer: '',
                    correctAnswer: correctAnswer,
                    validated: false,
                    result: '',
                    kind: data[i].kind,
                    blanks: blanks
                }
                questions.push(question);
                // console.log("i=" + i + ",data[i]=" + JSON.stringify(data[i]))
            }
            this.questions = questions;
            // 随机打乱题目
            this.randomQuestions();
            // 设置第一个
            this.setCurrent(0);
        },
        // 获取我的所有分类
        getMyCategories() {
            // this.loading = true;
            const url = this.curPrefixUrl + "/user/categories";
            axios.get(url).then((resp) => {
                const result = resp.data;

                this.categories = result.data;
            }).finally(() => {
                // this.loading = false;
            });
        },
        // 初始化值
        initValue() {
            // 是否开始练习
            this.doing = false;
            // 卡片边框颜色
            this.cardBorderColor = [];
            // 练习题目的方式
            this.questionMethod = {
                // 选择的题型
                checkboxQuestions: [],
                // 选择的分类
                categoryIds: [],
                // 答案验证方式
                validateMethod: null
            };
            // 当前题目在questions中的序号
            this.currentIdx = 0;
            // 完成了所有题目
            this.finished = false;
            // 答案比对方式是做一题立即比对
            this.isValidateNow = true;
            // 全部练习题目
            this.questions = [];
        },
        // 选择了当前选项
        selectChoice(index) {
            // console.log("index=" + index);
            // showAlert(this, '你选择了' + index);
            // console.log("finished=" + this.finished);
            if (this.finished) {
                return;
            }
            // 使用 Vue.set 方法来更改数组元素
            if (this.cardBorderColor[index] === myColor.blue) {
                Vue.set(this.cardBorderColor, index, myColor.default);
                // 移除选项
                let idx = this.currentSelected.indexOf(index);
                if (idx > -1) {
                    this.currentSelected.splice(idx, 1);
                }
            } else {
                Vue.set(this.cardBorderColor, index, myColor.blue);
                this.currentSelected.push(index);
            }
            // console.log(this.cardBorderColor);
        },
        // 生成选择题中我的答案
        genMyAnswerOfChoice() {
            let ans = '';
            let selected = this.currentSelected.sort();
            for (let i = 0; i < selected.length; i++) {
                ans += this.options[selected[i]];
            }
            return ans;
        },
        genMyAnswerOfChoiceByIdx(idx) {
            let ans = '';
            let selected = this.questions[idx].selected.sort();
            for (let i = 0; i < selected.length; i++) {
                ans += this.options[selected[i]];
            }
            return ans;
        },
        genMyAnswerOfBlankByIdx(idx) {
            let ans = '';
            for (let i = 0; i < this.questions[idx].blanks.length; i++) {
                ans += (this.questions[idx].blanks[i].trim() + ' ');
            }
            return ans;
        },
        // 生成结果
        genResultNow() {
            const myAnswer = this.currentMyAnswer.trim();
            const correctAnswer = this.currentCorrectAnswer.trim();
            // console.log("myAnswer=" + myAnswer + ",correctAnswer=" + correctAnswer)
            if (myAnswer === correctAnswer) {
                return '✔️'
            } else {
                return '❌';
            }
        },
        genResultByIdx(idx) {
            if (this.questions[idx].myAnswer.trim() === this.questions[idx].correctAnswer.trim()) {
                return '✔️'
            } else {
                return '❌';
            }
        },
        // 到达指定的题目
        toQuestion(idx) {
            this.currentIdx = idx;
            this.setCurrent(idx);
            // 查询题目对应的笔记
            if (this.doing && ((!this.isValidateNow && this.finished) || (this.isValidateNow && this.currentValidated))) {
                this.getNotesByQuestionId(this.currentQuestionId, this.currentIdx);
            }
        },
        // 点击了下一题
        nextQuestion() {
            // 存这一道题
            this.saveCurrent();
            // 去下一道题
            this.toQuestion(this.currentIdx + 1);
        },
        // 设置当前题目
        setCurrent(idx) {
            // console.log("idx=" + idx + ",questions[idx]" + JSON.stringify(this.questions[idx]));
            this.currentQuestionId = this.questions[idx].id;
            this.currentQuestion = this.questions[idx].question;
            this.currentChoices = this.questions[idx].choices;
            this.currentSelected = this.questions[idx].selected;
            this.currentMyAnswer = this.questions[idx].myAnswer;
            this.currentCorrectAnswer = this.questions[idx].correctAnswer;
            this.currentResult = this.questions[idx].result;
            this.currentValidated = this.questions[idx].validated;
            this.currentQuestionKind = this.questions[idx].kind;
            this.currentBlanks = this.questions[idx].blanks;
            // 恢复默认选项框
            for (let i = 0; i < this.currentChoices.length; i++) {
                Vue.set(this.cardBorderColor, i, myColor.default);
            }
            // 设置已选选项框
            for (let i = 0; i < this.currentSelected.length; i++) {
                let index = this.currentSelected[i];
                Vue.set(this.cardBorderColor, index, myColor.blue);
            }
        },
        // 随机打乱所有题目
        randomQuestions() {
            // console.log("前：questions=" + JSON.stringify(this.questions));
            this.shuffle(this.questions);
            // console.log("后：questions=" + JSON.stringify(this.questions));
        },
        // Fisher-Yates shuffle
        shuffle(array) {
            for (let i = array.length - 1; i > 0; i--) {
                // 从 0 到 i 的随机索引
                let j = Math.floor(Math.random() * (i + 1));
                // 交换元素 array[i] 和 array[j]
                [array[i], array[j]] = [array[j], array[i]];
            }
        },
        // 点击了上一题
        prevQuestion() {
            this.saveCurrent();
            // 去上一道题
            this.toQuestion(this.currentIdx - 1);
        },
        // 存当前题目到questions
        saveCurrent() {
            // 存这一道题
            this.questions[this.currentIdx].myAnswer = this.currentMyAnswer;
            this.questions[this.currentIdx].selected = this.currentSelected;
            this.questions[this.currentIdx].validated = this.currentValidated;
            this.questions[this.currentIdx].result = this.currentResult;
            for (let i = 0; i < this.currentBlanks.length; i++) {
                this.questions[this.currentIdx].blanks[i] = this.currentBlanks[i].trim();
            }
        },
        // 现在比对答案
        validateNow() {
            // showAlert(this, "this.currentSelected=" + this.currentSelected);
            // 设置当前已经比对答案
            this.currentValidated = true;
            // 题目是选择题
            if (this.currentQuestionKind === questionKind.choice) {
                // 我的答案
                this.currentMyAnswer = this.genMyAnswerOfChoice();
                // 正确答案
                this.currentCorrectAnswer = this.questions[this.currentIdx].correctAnswer;
                // 结果
                this.currentResult = this.genResultNow();
            }
            // 题目是填空题
            else if (this.currentQuestionKind === questionKind.blank) {
                // 我的答案
                this.currentMyAnswer = this.genMyAnswerOfBlankByIdx(this.currentIdx);
                // 正确答案
                this.currentCorrectAnswer = this.questions[this.currentIdx].correctAnswer;
                // 结果
                this.currentResult = this.genResultNow();
            }
            // 题目是判断题
            else if (this.currentQuestionKind === questionKind.judge) {
                // 正确答案
                this.currentCorrectAnswer = this.questions[this.currentIdx].correctAnswer;
                // 结果
                this.currentResult = this.genResultNow();
            }
            // 解答题
            else if (this.currentQuestionKind === questionKind.solve) {
                // 正确答案
                this.currentCorrectAnswer = this.questions[this.currentIdx].correctAnswer;
                // 结果
                this.currentResult = this.solveResult;
            }
            // 如果是最后一题设置finished
            if (this.currentIdx === this.questions.length - 1) {
                this.finished = true;
            }
            // 查询当前题目笔记
            // console.log("currentQuestionId=" + this.currentQuestionId);
            // console.log("currentIdx=" + this.currentIdx);
            this.getNotesByQuestionId(this.currentQuestionId, this.currentIdx);
        },
        // 逐一对比全部答案
        validateAll() {
            // 存这一题
            this.saveCurrent();
            // 已完成
            this.finished = true;
            for (let i = 0; i < this.questions.length; i++) {
                // 设置已验证答案
                this.questions[i].validated = true;
                // 选择题
                if (this.questions[i].kind === questionKind.choice) {
                    // 我的答案
                    this.questions[i].myAnswer = this.genMyAnswerOfChoiceByIdx(i);
                    // 结果
                    this.questions[i].result = this.genResultByIdx(i);
                }
                // 填空题
                else if (this.questions[i].kind === questionKind.blank) {
                    // 我的答案
                    this.questions[i].myAnswer = this.genMyAnswerOfBlankByIdx(i);
                    // 结果
                    this.questions[i].result = this.genResultByIdx(i);
                }
                // 判断题
                else if (this.questions[i].kind === questionKind.judge) {
                    // 结果
                    this.questions[i].result = this.genResultByIdx(i);
                }
                // 解答题
                else if (this.questions[i].kind === questionKind.solve) {
                    // 结果
                    this.questions[i].result = this.solveResult;
                }
            }
            // 前往第一题
            this.toQuestion(0);
            // console.log(this.questions);
        },
        isLastQuestion() {
            return this.currentIdx === this.questions.length - 1;
        },
        isFirstQuestion() {
            return this.currentIdx === 0;
        },
        // 获取题目对应的笔记
        getNotesByQuestionId(questionId, currentIdx) {
            // console.log("questionId=" + questionId + ", currentIdx=" + currentIdx);
            this.loadingGetNotes = true;
            const url = prefixUrl + "/note/user/notes/" + questionId;
            axios.get(url).then((resp) => {
                const result = resp.data;

                this.currentNotes = result.data;
                this.allNotes[currentIdx] = result.data;
            }).catch(() => {
            }).finally(() => {
                this.loadingGetNotes = false;
            });
        },
        cancelEditNote() {
            this.updatingNote = false;
        },
        // 修改笔记完成
        finishEditNote() {
            const noteUpdateDTO = {
                id: this.updateNote.id,
                content: this.updateNote.content,
                open: this.updateNote.open,
            };
            const url = prefixUrl + "/note/user/notes";
            this.loadingEditNote = true;
            axios.put(url, noteUpdateDTO).then((resp) => {
                const result = resp.data;
                if (result.code === resultConstant.success) {
                    showMsg(this, '修改成功');
                    // 获取笔记
                    // console.log("currentQuestionId=" + this.currentQuestionId + ", currentIdx=" + this.currentIdx);
                    this.getNotesByQuestionId(this.currentQuestionId, this.currentIdx);
                    // this.getNotesByQuestionId(this.currentQuestion.id);
                } else {
                    showMsg(result.msg);
                }
            }).catch((error) => {
                showMsg(error);
            }).finally(() => {
                this.updatingNote = false;
                this.loadingEditNote = false;
            });
        },
        // 修改笔记
        editNote(note) {
            // showAlert(this, id);
            this.updateNote = {
                id: note.id,
                content: note.content,
                open: note.open + ""
            };
            this.updatingNote = true;
        },
        // 展示添加笔记卡片
        showAddNote() {
            this.showAddNoteCard = !this.showAddNoteCard;
        },
        // 添加笔记
        addNote() {
            let noteAddDTO = {
                questionId: this.currentQuestionId,
                content: this.note.content,
                open: openStatus.notOpen
            };
            if (this.note.open) {
                noteAddDTO.open = openStatus.open;
            }
            const url = prefixUrl + "/note/user/notes";
            // 加载
            this.loadingAddNote = true;
            axios.post(url, noteAddDTO).then((resp) => {
                const result = resp.data;


                if (result.code === resultConstant.success) {
                    // 清空
                    this.note = {};
                    // 提示
                    showSuccessMsg(this, "笔记添加成功");
                    // 查询笔记
                    this.getNotesByQuestionId(this.currentQuestionId, this.currentIdx);
                } else {
                    showErrorMsg(this, result.msg);
                }
            }).catch(() => {
            }).finally(() => {
                this.loadingAddNote = false;
            });
        },
    },
    created() {
        // 查询我的分类
        this.getMyCategories();

        // console.log("this.$data=" + JSON.stringify(this.$data));
        // 在页面加载时读取sessionStorage里的状态信息
        let dataString = sessionStorage.getItem(storageKey.doQuestionData);
        // console.log("dataString=" + JSON.stringify(dataString));
        let data = JSON.parse(dataString);
        // console.log("data=" + JSON.stringify(data));
        if (data) {
            // 有数据直接获取
            Object.assign(this.$data, data)
        }
        // 在页面刷新时将数据保存到sessionStorage里
        window.addEventListener('beforeunload', () => {
            sessionStorage.setItem(storageKey.doQuestionData, JSON.stringify(this.$data));
        })
    },
    beforeDestroy() {
        //销毁前先移除，否则跳转到其它地方，sessionStorage里面依旧存在key
        // sessionStorage.removeItem(storageKey.doQuestionData);
    }
});